//
//  SendADViewController.m
//  iStore
//
//  Created by MacDev on 15/5/11.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "SendADViewController.h"
#import "CostViewController.h"
#import "SendADTableViewCell.h"
#import "RequestEngine.h"

#define kadverSum @"^[0-9]*$"
@interface SendADViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
{
    NSMutableDictionary *sendPriceDic;
    NSMutableArray *tableArray;
}
@end

@implementation SendADViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"精准投放";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(back:)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    tableArray = [[NSMutableArray alloc]init];
    _adverSumTextFile.enabled = NO;
//    _adverSumTextFile.text = @"10";
    
    [_confirm setBackgroundImage:[UIImage imageNamed:@"Rectangle_6"] forState:UIControlStateHighlighted];
    
    sendPriceDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"",@"radius",@"",@"timeScope",@"",@"activityPeriod",@"",@"carCluster",_type,@"type",@"0",@"shopID",@"",@"adverSum",@"IOS",@"appKey" ,nil];
    NSString *userID = [[NSUserDefaults standardUserDefaults]objectForKey:kUserId];
    UIActivityIndicatorView *active = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    active.center = CGPointMake(ScreenWidth/2, 40);
    [_tableView addSubview:active];
    [active startAnimating];
    
    [RequestEngine RequestEngineWithDic:@{@"userID":userID} URL:@"/shop/getMyShops" completed:^(NSString *errorcode, NSDictionary *resultDict) {
        if ([errorcode isEqualToString:@"0"]) {
            for (id obj in resultDict) {
                [tableArray addObject:obj];
            }
            if (tableArray.count == 0) {
                alert(@"亲！您现在尚未注册添加店铺信息或您添加的店铺信息正在审核中暂不能进行广告投放操作");
                [active stopAnimating];
                return;
            }
            [_tableView reloadData];
            NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [_tableView selectRowAtIndexPath:firstPath animated:NO scrollPosition:UITableViewScrollPositionNone];
            sendPriceDic[@"shopID"] = [tableArray objectAtIndex:0][@"id"];
            
            
        }
        [active stopAnimating];
    }];
    
}

#pragma  mark - tableView --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    SendADTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"SendADTableViewCell" owner:self options:nil]lastObject];
    }
    cell.selectedBackgroundView = [[UIView alloc]initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:250.0/255 green:134.0/255 blue:180.0/255 alpha:0.3];
    
    [cell refreshData:[tableArray objectAtIndex:indexPath.row]];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [tableArray objectAtIndex:indexPath.row];
    sendPriceDic[@"shopID"] = dic[@"id"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)back:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma  mark - button --
- (IBAction)clickRadius:(UIButton *)sender {
    sendPriceDic[@"radius"] = [NSString stringWithFormat:@"%ld",(long)sender.tag];
    [self sectionChoose:sender StartNum:1 StopNum:3];
}

- (IBAction)clickTimeScope:(UIButton *)sender {
    sendPriceDic[@"timeScope"] = [NSString stringWithFormat:@"%ld",(long)sender.tag];
    [self sectionChoose:sender StartNum:3 StopNum:8];
}

- (IBAction)clickActivity:(UIButton *)sender {
    sendPriceDic[@"activityPeriod"] = [NSString stringWithFormat:@"%ld",(long)sender.tag];
    [self sectionChoose:sender StartNum:8 StopNum:11];
}

- (IBAction)clickCarCluster:(UIButton *)sender {
    if (sender.tag == 11) {
        sendPriceDic[@"carCluster"] = @"11";
        [self changeChoose:sender];
    }
    else if (sender.tag == 12) {
        sendPriceDic[@"carCluster"] = @"12";
        [self changeChoose:sender];
    }
    else if (sender.tag == 13) {
        sendPriceDic[@"carCluster"] = @"13";
        [self changeChoose:sender];
    }
}
- (void)sectionChoose:(UIButton*)btn StartNum:(NSInteger)startNum StopNum:(NSInteger)stopNum
{
    [self changeChoose:btn];
    NSInteger i;
    for (i =startNum; i<stopNum; i++) {
        if (i != btn.tag) {
            [self radioButton:i];
        }
    }
}
- (IBAction)clickAdverSum:(UIButton *)sender {
    if (sender.tag == 101) {
        int temp = [_adverSumTextFile.text intValue];
        if (temp > 0) {
            _adverSumTextFile.text = [NSString stringWithFormat:@"%d",--temp];
            
        }
    }
    else if(sender.tag == 102){
        int temp = [_adverSumTextFile.text intValue];
        _adverSumTextFile.text = [NSString stringWithFormat:@"%d",++temp];
        
    }
    
    if ([_adverSumTextFile.text intValue] > 0) {
        [_buttonImage setImage:[UIImage imageNamed:@"minus-red_1"] forState:UIControlStateNormal];
    }
    else {
        [_buttonImage setImage:[UIImage imageNamed:@"减号"] forState:UIControlStateNormal];
    }
    
}
- (void)radioButton:(NSInteger)tag
{
    UIButton *temp = (UIButton*)[self.view viewWithTag:tag];
    if (temp.selected == YES) {
        [self changeChoose:temp];
    }
}

-(UIButton*)getButton:(NSInteger)tag
{
    return (UIButton*)[self.view viewWithTag:tag];
}

- (void)changeChoose:(UIButton*)button
{
    if (button.selected == YES) {
        [button setBackgroundImage:[UIImage imageNamed:@"Check-box_1.png"] forState:UIControlStateNormal];
        button.selected = NO;
    }
    else{
        [button setBackgroundImage:[UIImage imageNamed:@"Check-box.png"] forState:UIControlStateNormal];
        button.selected = YES;
    }
}
- (IBAction)textFileChange:(id)sender {
    UITextField *file = (UITextField*)sender;
    if ([file.text integerValue] < 0 || [file.text integerValue] > 1000) {
        alert(@"投放数量为0~1000/千条");
    }
}

- (IBAction)certernButton:(id)sender {
    if ([[NSString stringWithFormat:@"%@",sendPriceDic[@"shopID"]] isEqualToString:@"0"]) {
        alert(@"请选择店址");
        return;
    }
    if (!([self getButton:1].selected == YES || [self getButton:2].selected == YES)) {
        alert(@"请选择覆盖半径");
        return;
    }
    else if (!([self getButton:3].selected == YES || [self getButton:4].selected == YES || [self getButton:5].selected == YES || [self getButton:6].selected == YES || [self getButton:7].selected == YES)) {
        alert(@"请选择时段");
        return;
    }
    else if (!([self getButton:8].selected == YES || [self getButton:9].selected == YES || [self getButton:10].selected == YES)) {
        alert(@"请选择活动周期");
        return;
    }
    else if (!([self getButton:11].selected == YES || [self getButton:12].selected == YES || [self getButton:13].selected == YES)) {
        alert(@"请选择车辆特征");
        return;
    }
    else if ([_adverSumTextFile.text isEqualToString:@"0"] || [_adverSumTextFile.text isEqualToString:@""]) {
        alert(@"请选择投放数量");
        return;
    }
    if (![self regexFlagWith:kadverSum withParameter:_adverSumTextFile.text]) {
        alert(@"请输入投放数量");
        return;
    }
    else{
        CostViewController * vc = [[CostViewController alloc]init];
        sendPriceDic[@"adverSum"] = _adverSumTextFile.text;
        vc.priceDict = sendPriceDic;
        vc.radioText = _radioText;
        [_adverSumTextFile resignFirstResponder];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark --textfield取消键盘--
- (void)touchScrollView:(UITapGestureRecognizer*)recognizer
{
    if (![self regexFlagWith:kadverSum withParameter:_adverSumTextFile.text]) {
        alert(@"请输入投放数量");
        return;
    }
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame =self.view.frame;
        frame.origin.y = 0.0;
        self.view.frame = frame;
    }];
    
    if ([_adverSumTextFile.text integerValue] < 0 || [_adverSumTextFile.text integerValue] > 99999) {
        [[[UIAlertView alloc]initWithTitle:@"提示" message:@"投放数量为0~1000/千条" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        return;
    }
    
    [_adverSumTextFile resignFirstResponder];
    [_scrollView removeGestureRecognizer:recognizer];
}
- (IBAction)textFileBegin:(UITextField *)sender {
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchScrollView:)];
    [recognizer setNumberOfTapsRequired:1];
    [recognizer setNumberOfTouchesRequired:1];
    [_scrollView addGestureRecognizer:recognizer];
    _adverSumTextFile.text = @"";
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = -self.view.bounds.size.height/3;
        self.view.frame = frame;
    }];
}

- (IBAction)expandButton:(UIButton *)sender {
    if (sender.tag / 100 == 2) {
        NSInteger inter = sender.tag % 100;
        [self clickRadius:(UIButton*)[self.view viewWithTag:inter]];
    }
    else if (sender.tag / 100 == 3) {
        NSInteger inter = sender.tag % 100;
        [self clickTimeScope:(UIButton*)[self.view viewWithTag:inter]];
    }
    else if (sender.tag / 100 == 4) {
        NSInteger inter = sender.tag % 100;
        [self clickActivity:(UIButton*)[self.view viewWithTag:inter]];
    }
    else if (sender.tag / 100 == 5) {
        NSInteger inter = sender.tag % 100;
        [self clickCarCluster:(UIButton*)[self.view viewWithTag:inter]];
    }
    
}
//正则表达式的判断
- (BOOL) regexFlagWith:(NSString *)regex withParameter:(NSString *)parameter{
    
    NSPredicate *pass = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [pass evaluateWithObject:parameter];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y = -self.view.bounds.size.height/3;
            self.view.frame = frame;
        }];
    }
}
@end
